<?php
namespace classlib\core\view;
class cvs extends view_abstract {
	private $smart;
	function __construct($params=null) {
		$this->smart = array('data'=>array());
	}

	/**
	 * 变量赋值
	 * @param string $key
	 * @param mix    $val
	 * @return view_abstract
	 */
	public function assign($key, $val) {
		$this->smart[$key] = $val;
		return $this;
	}
	
	/**
	 * 变量赋值引用赋值
	 * @param string $key
	 * @param mix $val
	 * @return view_abstract
	 */
	public function assign_by_ref($key, &$val) {
		$this->smart[$key] = &$val;
		return $this;
	}

	/**
	 * 已经分配的变量的获取 默认取所有
	 * @param string $key
	 * @return mix
	 */
	public function get_template_vars($key=false) {
		if($key) {
			$data = isset($this->smart[$key])? $this->smart[$key]:false;
			return $data;
		}
		return $this->smart;
	}
	
	/**
	 * 将要输出的资料获取
	 * @param string  $tpl
	 * @param boolean $iscache
	 * @return string
	 */
	public function fetch($tpl=false, $iscache=false) {
		$ua    = $_SERVER['HTTP_USER_AGENT'];
		if(empty($tpl)) {
			$tpl = date('YmdHis');
		}
        $tpl   = urlencode($tpl);
        header("Content-Type: text/csv");
        if(preg_match("/MSIE/i", $ua)) {
            header('Content-Disposition: attachment; filename="'.$tpl.'.csv"');
        } else if(preg_match("/Firefox/i", $ua)) {
            header("Content-Disposition: attachment; filename*=\"utf8''".$tpl.'.csv"');
        } else {
            header('Content-Disposition: attachment; filename="'.$tpl.'.csv"');
        }
        $list  = '';
		if (!empty($this->smart['data']) && !empty($this->smart['header'])) {
			//遍历组织 拼接头部
			$keys  = array_keys($this->smart['header']);
			$oitem = array();
			foreach ($keys as $idx=>$key) {
				$oitem[$idx] = $this->smart['header'][$key];
			}
			$list[] .= implode(',', $oitem);
			//遍历拼接数据部分
		    foreach($this->smart['data'] as &$item) {
		    	$oitem = array();
		    	foreach ($keys as $idx=>$key) {
		    		$oitem[$idx] = isset($item[$key])? $item[$key]:'';
		    	}
			    $list[] .= implode(',', $oitem);
		    }
		}
	    $str = implode("\r\n", $list);
	    $str = mb_convert_encoding($str, 'gbk', 'utf-8');
	    return $str;
	}

	/**
	 * 重载Smarty输出的资料输出
	 * @param string  $tpl
	 * @param int     $caching 
	 * @param string  $cacheid  区别同一个页面不同展示模版
	 * @param int     $lifetime
	 * @see Smarty  $caching
	 */
	public function display($tpl=false, $caching=0, $cacheid=null, $lifetime=3600) {
		parent::display();
		echo $this->fetch($tpl);
	}
}